package com.gonsin.venus.sdk.client;

import com.gonsin.venus.sdk.GonsinConfig;
import com.gonsin.venus.sdk.IGonsinClient;
import com.gonsin.venus.sdk.exceptions.ApiException;
import com.gonsin.venus.sdk.exceptions.ErrorCodes;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 公信访问类
 */
public class GonsinClient implements IGonsinClient {

    private GonsinConfig config;

    private TokenManager tokenManager;

    public GonsinClient(GonsinConfig config) {
        this.config = config;
        this.tokenManager = new TokenManager();
        this.tokenManager.init(config);
    }

    /**
     * 发送get请求
     */
    @Override
    public String get(String url, Map<String, Object> params) throws ApiException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(config.toUrl(url));
        String response = null;
        try {
            URIBuilder uriBuilder = null;
            try {
                uriBuilder = new URIBuilder(config.toUrl(url));
            } catch (URISyntaxException e) {
                e.printStackTrace();
                throw new ApiException(ErrorCodes.URL_ERROR, "路径格式错误");
            }
            if(params != null){
                URIBuilder finalUriBuilder = uriBuilder;
                params.forEach((k, v) -> {
                    finalUriBuilder.addParameter(k, v.toString());
                });
            }
            TokenBo tokenBo = tokenManager.getToken();
            httpGet.addHeader("x-token", tokenBo.getXToken());
            response = client.execute(httpGet, res -> {
                InputStream input = res.getEntity().getContent();

                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(input));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                String str = sb.toString();
                return str;
            });
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApiException(ErrorCodes.HTTP_ERROR, "请求过程中出现异常");
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }


    /**
     * 发送post请求表单
     */
    @Override
    public String post(String url, Map<String, Object> params) throws ApiException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(config.toUrl(url));
        String response = null;
        try {
            TokenBo tokenBo = tokenManager.getToken();

            List<NameValuePair> p = new ArrayList<>();
            if(params != null){
                params.forEach((k, v) -> {
                    p.add(new BasicNameValuePair(k, v.toString()));
                });
            }
            post.setEntity(new UrlEncodedFormEntity(p));
            post.addHeader("x-token", tokenBo.getXToken());
            response = client.execute(post, res -> {
                InputStream input = res.getEntity().getContent();

                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(input));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                String str = sb.toString();
                return str;
            });
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApiException(ErrorCodes.HTTP_ERROR, "请求过程中出现异常");
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }


    /**
     * 发送post请求
     */
    @Override
    public String postJson(String url, String json) throws ApiException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(config.toUrl(url));
        String response = null;
        try {
            TokenBo tokenBo = tokenManager.getToken();
            post.setEntity(new StringEntity(json));
            post.addHeader("x-token", tokenBo.getXToken());
//            post.addHeader("x-key", tokenBo.getXKey());
            response = client.execute(post, res -> {
                InputStream input = res.getEntity().getContent();

                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(input));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                String str = sb.toString();
                return str;
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
